import React from 'react';
import style from '@/assets/css/index.module.css';
import TabBar from '@/components/TabBar';
import type { coupon } from '@/types/coupon';
import { sleep } from 'antd-mobile/es/utils/sleep';
import type room from '@/types/room';

const Index = () => {
  // 状态管理
  const [search, SetSearch] = useState<string>(''); // 搜索框
  const [CouponList, SetCouponList] = useState<coupon[]>([]); // 优惠券数据列表
  const [list, SetList] = useState<room[]>([]); // 房间数据列表
  const [hasMore, SetHasMore] = useState<boolean>(true); // 加载状态
  const [page, SetPage] = useState<number>(1); // 分页
  const [ListCount, SetListCount] = useState<number>(0); // 房间数据列表的长度

  // 挂载前 获取轮播图数据
  useEffect(() => {
    GetCouponData();
  }, []);

  // 获取优惠券数据
  const GetCouponData = async () => {
    // 直接发起请求
    const result = await React.Http.post('/index/coupon');
    if (result.code === 1) {
      SetCouponList(result.data);
    }
  }

  // 获取房间数据
  const GetRoomData = async () => {
    // 组装参数
    const params = {
      page,
      search
    }
    // 发起请求
    const result = await React.Http.post('/room/index', params);
    // 处理请求结果
    if (result.code === 1) {
      SetList(v => {
        const newList = [...v, ...result.data.list];
        SetListCount(newList.length);
        return newList;
      })
      // 结束加载条件
      if (result.data.count === ListCount) {
        SetHasMore(false);
        return;
      }
      // 继续加载
      SetHasMore(true);
      SetPage(page => page + 1);
    } else {
      React.fail(result.msg);
      // 加载完成
      SetHasMore(false);
    }
  }

  // 下拉刷新
  const OnRefresh = async () => {
    await sleep(1000);
    SetList([]);
    SetPage(1);
    SetHasMore(true);
  }

  // 上拉加载
  const OnLoadMore = async () => {
    await sleep(1000);
    await GetRoomData();
  }

  // 搜索事件
  const OnSearch = async () => {
    await sleep(1000);
    SetList([]);
    SetPage(1);
    SetHasMore(true);
  }

  // 优惠券轮播图
  const CouponSwiper = useCallback(() => {
    // 有优惠券数据才显示
    if (CouponList.length > 0) {
      return (
        <>
          <React.UI.Swiper autoplay={true} loop={true}>
            {CouponList.map(item => (
              <React.UI.Swiper.Item key={item.id}>
                <React.UI.Image src={item.thumb_cdn} width={'100%'} height={240} fit='cover' onClick={() => React.navigate(`/coupon/info?couponid=${item.id}`)} />
              </React.UI.Swiper.Item>
            )
            )}
          </React.UI.Swiper>
        </>
      )
    }
  }, [CouponList])

  return (
    <>
      {/* <!-- 导航 --> */}
      <div className={style.top}>
        <div>首页</div>
      </div>
      {/* <!-- 轮播图的优惠券 --> */}
      <CouponSwiper />

      <React.UI.SearchBar
        value={search}
        clearable
        placeholder="请输入关键词搜索"
        onChange={(val: string) => SetSearch(val)}
        onSearch={OnSearch}
        style={{
          '--border-radius': '100px',
          '--background': '#eee',
          '--height': '32px',
          '--padding-left': '12px',
          'margin': '0 auto',
          'marginTop': '10px',
          'width': '90%',
        }}
      />

      <div className={style.hotellist}>
        {/* 下拉刷新 */}
        <React.UI.PullToRefresh onRefresh={OnRefresh}>
          {list.map((item: room, index: number) => {
            return (
              <div className={style.item} key={index}>
                <NavLink to={`/room/info?roomid=${item.id}`}>
                  <div className={style.images}>
                    <div className={style.swipers}>
                      <img src={item.thumb_text} alt="" />
                    </div>
                    <div className={style.title}>{item.name}</div>
                  </div>
                  <div>
                    <div className={style.item_top}>
                      {item.flag && JSON.parse(item.flag).map((val: string, idx: number) => {
                        return (
                          <span key={idx}>{val}</span>
                        )
                      })}
                    </div>
                    <div className={style.item_bot}>
                      <div className={style.font}>
                        <span className={style.price}>￥{item.price}/晚</span>
                        {/* <span className={style.market_price}>￥80.00/晚</span> */}
                      </div>
                      <div className={style.btn}>立即预定</div>
                    </div>
                  </div>
                </NavLink>
              </div>
            )
          })}

          {/* 上拉加载 */}
          <React.UI.InfiniteScroll loadMore={OnLoadMore} hasMore={hasMore} />
        </React.UI.PullToRefresh>
      </div>

      <div style={{ height: '55px' }}></div>

      <TabBar />
    </>
  )
}

export default Index;